package futurecallableexecutor;

import java.util.concurrent.*;

/**
 * @author DELL
 * @create 2017-09-22 15:14
 */
public class MultithreadMaxFinder {
    public static int max(int[] data) throws ExecutionException, InterruptedException {
        if(data.length == 1) {
            return data[0];
        } else if (data.length == 0) {
            throw new IllegalArgumentException();
        }

        //将任务分为两部分
        FindMaxTask task1 = new FindMaxTask(data, 0, data.length / 2);
        FindMaxTask task2 = new FindMaxTask(data, data.length / 2, data.length);

        //创建2个线程
        ExecutorService service = Executors.newFixedThreadPool(2);

        /*Future<Integer> future1 = service.submit(task1);
        Future<Integer> future2 = service.submit(task2);*/

        FutureTask<Integer> future1 = new FutureTask<>(task1);
        FutureTask<Integer> future2 = new FutureTask<>(task2);
        service.submit(future1);
        service.submit(future2);
        return Math.max(future1.get(), future2.get());
    }
}
